<template>
  <div class="cart">
    <Header/>
    <div class="main">
      <div class="cart-title">
        <h3>我的购物车 <span> 共{{this.$store.state.cart.count}}门课程</span></h3>
      </div>
      <div class="cart-info">
        <el-table
          :data="courseData"
          style="width:100%"
          ref="multipleTable"
          @select="currentSelected"
          @selection-change="selectionChange">
          <el-table-column type="selection" label="" width="87"></el-table-column>
          <el-table-column label="课程" width="540">
            <template slot-scope="scope">
              <div class="course-box">
                <img :src="$settings.Host + scope.row.course_img" alt="">
                <router-link :to="'/detail?id='+scope.row.id">{{scope.row.name}}</router-link>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="有效期" width="216">
            <template slot-scope="scope">
              <el-form ref="form" label-width="60px">

                <el-select v-model="scope.row.expire" @change="ChangeExpire(scope.row)" placeholder="请选择有效期">
                  <el-option v-for="item in scope.row.expire_list" :key="item.timer" :label="item.title"
                             :value="item.timer"></el-option>
                </el-select>

              </el-form>
            </template>
          </el-table-column>
          <el-table-column label="单价" width="162">
            <template slot-scope="scope">¥{{ scope.row.price.toFixed(2) }}</template>
          </el-table-column>
          <el-table-column label="操作" width="162">
            <template slot-scope="scope">
              <a @click="CartDel(scope.row, scope.row.name)">删除</a>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="cart-bottom">
        <div class="select-all">
          <el-checkbox>全选</el-checkbox>
        </div>
        <div class="delete-any"><img src="../../static/img/ico3.png" alt="">删除</div>
        <div class="cart-bottom-right">
          <span class="total">
            总计：¥
            <span>{{total_price}}</span>
          </span>
          <span class="go-pay" @click="gotopay">去结算</span>
        </div>
      </div>
    </div>
    <Footer/>
  </div>
</template>

<script>
  import Header from "./common/Header"
  import Footer from "./common/Footer"

  export default {
    name: "Cart",
    data() {
      return {
        // expire: 3,
        // expire_list: [
        //   {title: "一个月有效", id: 1},
        //   {title: "两个月有效", id: 2},
        //   {title: "三个月有效", id: 3},
        //   {title: "永久有效", id: -1},
        // ],
        courseData: [],
        selection: [],
        total_price: 0.00,
      }
    },
    watch: {
      selection() {
        this.getTotalPrice();
      },
      courseData() {
        this.getTotalPrice();
      },
    },
    created() {
      if (!this.$store.state.user.token) {
        this.$confirm('对不起，您尚未登录！请登录', '提示').then(() => {
          this.$router.push('/login');
        }).catch(() => {
          this.$router.go(-1);
        });
      } else {
        this.$axios.get(this.$settings.Host + '/cart/course/', {
          headers: {
            'Authorization': 'jwt ' + this.$store.state.user.token
          }
        }).then(response => {
          this.courseData = response.data;
          this.$store.state.cart.count = response.data.length;
          setTimeout(() => {
            let expire_data = [];
            this.courseData.forEach(course => {
              course.expire_list.forEach(row => {
                expire_data[row.timer] = row.title;
              });
            });
            this.courseData.forEach(row => {
              if (row.is_select) {
                this.$refs.multipleTable.toggleRowSelection(row);
              }
              row.expire = expire_data[row.expire];
            });

            // let text_expire_list = [];
            // for (let i = 0; i < this.expire_list.length; i++) {
            //   text_expire_list[this.expire_list[i].id] = this.expire_list[i].title;
            // }
            // for (let i = 0; i < this.courseData.length; i++) {
            //   // 设置选中效果
            //   this.$refs.multipleTable.toggleRowSelection(this.courseData[i], this.courseData[i].is_select);
            //   // 修改有效期的显示值
            //   this.courseData[i].expire = text_expire_list[this.courseData[i].expire];
            // }
          }, 0);
        }).catch(error => {
          let status = error.response.status;
          if (status === 401) {
            this.$store.state.user.token = null;
            sessionStorage.removeItem('token');
            localStorage.removeItem('token');
            let _this = this;
            this.$alert('您尚未登录或登录超时！请重新登录', '警告', {
              callback() {
                _this.$router.push('/login');
              }
            })
          }
        })
      }
    },
    methods: {
      CartDel(course, course_name) {
        this.$confirm(`您确定要从购物车删除<<${course_name}>>这个课程吗？`, '提示').then(() => {
          let course_id = course.id;
          this.$axios.delete(this.$settings.Host + '/cart/course/', {
            params: {course_id: course_id},
            headers: {'Authorization': 'jwt ' + this.$store.state.user.token},
          }).then(response => {
            let index = this.courseData.indexOf(course);
            this.courseData.splice(index, 1);
            this.$message('删除成功')
          }).catch(error => {
            console.log(error.response)
          });
        }).catch(() => {
        })
      },
      currentSelected(selection, row) {
        let is_select = true;
        if (selection.indexOf(row) === -1) {
          is_select = '';
        }
        let course_id = row.id;
        this.$axios.put(this.$settings.Host + '/cart/course/', {
          course_id: course_id,
          is_select: is_select,
        }, {
          headers: {
            'Authorization': 'jwt ' + this.$store.state.user.token
          }
        }).then(response => {
          this.$message(response.data.message, '提示');
        }).catch(error => {
          console.log(error.response)
        })
      },
      ChangeExpire(course) {
        let course_id = course.id;
        let expire = course.expire;
        this.$axios.patch(this.$settings.Host + '/cart/course/', {
          course_id,
          expire,
        }, {
          headers: {
            'Authorization': 'jwt ' + this.$store.state.user.token
          },
        }).then(response => {
          course.price = response.data.price;
          this.getTotalPrice();
          this.$message(response.data.message, '提示');
        });
      },
      getTotalPrice() {
        let total = 0;
        this.selection.forEach(row => {
          total += row.price;
        });
        this.total_price = total.toFixed(2);
        if (this.total_price<0){this.total_price=0}
      },
      selectionChange(data) {
        this.selection = data;
      },
      gotopay() {
        this.$axios.post(this.$settings.Host + '/orders/', {}, {
          headers: {
            'Authorization': 'jwt ' + this.$store.state.user.token
          }
        }).then(response => {
          this.$message(response.data.message, '提示', {
        });
           this.$router.push(`/orders/${response.data.order}`)
        }).catch(error => {
          console.log(error.response)
        })
      }
    },
    components: {Header, Footer}
  }
</script>

<style scoped>
  .main {
    width: 1200px;
    margin: 0 auto;
    overflow: hidden; /* 解决body元素和标题之间的上下外边距的塌陷问题 */
  }

  .cart-title h3 {
    font-size: 18px;
    color: #666;
    margin: 25px 0;
  }

  .cart-title h3 span {
    font-size: 12px;
    color: #d0d0d0;
    display: inline-block;
  }

  .course-box img {
    max-width: 175px;
    max-height: 115px;
    margin-right: 35px;
    vertical-align: middle;
  }

  .cart-bottom {
    overflow: hidden;
    height: 80px;
    background: #F7F7F7;
    margin-bottom: 300px;
    margin-top: 50px;
  }

  .select-all {
    float: left;
    margin-right: 58px;
    line-height: 80px;
  }

  .delete-any {
    cursor: pointer;
    float: left;
    line-height: 80px;
  }

  .delete-any img {
    width: 18px;
    height: 18px;
    vertical-align: middle;
    padding-right: 15px;
  }

  .cart-bottom-right {
    float: right;
    text-align: right; /* 文本右对齐 */
  }

  .total {
    margin-right: 62px;
    font-size: 18px;
    color: #666;
  }

  .go-pay {
    outline: none;
    background: #ffc210;
    display: inline-block;
    padding: 27px 50px;
    font-size: 18px;
    cursor: pointer;
    color: #fff;
  }
</style>
